<!doctype html>
<script src="../../resources/testharness.js"></script>
<script src="../../resources/testharnessreport.js"></script>
<script src="../assert_selection.js"></script>
<script>
function doubleClick(selection) {
    const start = selection.document.querySelector('s');
    const end = selection.document.querySelector('e');

    eventSender.mouseMoveTo(
        selection.computeLeft(start),
        selection.computeTop(start) + 3);
    // Double-click to select at word-granularity to workaround eventSender
    // bug with selecting text at character granularity (i.e. that it just
    // doesn't work).
    eventSender.mouseDown();
    eventSender.mouseUp();
    eventSender.mouseDown();
    eventSender.mouseMoveTo(
        selection.computeLeft(end),
        selection.computeTop(end) + 3);
    eventSender.mouseUp();
}

function extend(selection, direction, unit) {
    selection.modify('extend', direction, unit);
}

for (const behavior of ['android', 'mac', /*'unix', 'win'*/]) {
    const steps = [
        { input: 'a <s>bc</s><br>d <e>ef</e><br>ghi' },
        {
            // step 1
            action: selection => doubleClick(selection),
            mac: 'a <s>^bc</s><br>d <e>ef|</e><br>ghi',
            others: 'a <s>^bc</s><br>d <e>ef|</e><br>ghi',
        },
        {
            // step 2
            action: selection => extend(selection, 'backward', 'character'),
            mac: 'a| <s>bc</s><br>d <e>ef^</e><br>ghi',
            others: 'a <s>^bc</s><br>d <e>e|f</e><br>ghi',
        },
        {
            // step 3
            action: selection => extend(selection, 'forward', 'character'),
            mac: 'a <s>|bc</s><br>d <e>ef^</e><br>ghi',
            others: 'a <s>^bc</s><br>d <e>ef|</e><br>ghi',
        },
        {
            // step 4
            action: selection => extend(selection, 'forward', 'line'),
            mac: 'a <s>bc</s><br>d <e>|ef^</e><br>ghi',
            others: 'a <s>^bc</s><br>d <e>ef</e><br>ghi|',
        },
        {
            // step 5
            action: selection => extend(selection, 'backward', 'line'),
            mac: 'a <s>|bc</s><br>d <e>ef^</e><br>ghi',
            others: 'a <s>^bc</s><br>d <e>ef|</e><br>ghi',
        },
    ];
    for (let step = 1; step < steps.length; ++step) {
        selection_test(
            `<div>${steps[0].input}</div>`,
            selection => {
                if (!window.eventSender)
                    throw 'This test requires eventSender.';
                if (!window.internals)
                    throw 'This test requires internals.';
                internals.settings.setEditingBehavior(behavior);
                for (let i = 1; i <= step; ++i)
                    steps[i].action(selection);
            },
            behavior === 'mac'
                ? `<div>${steps[step].mac}</div>`
                : `<div>${steps[step].others}</div>`,
            `${behavior}: step ${step} ${steps[step].action}`);
    }
}
</script>
